import dbx;
import webx;
import stdx;
import json;


class PageParser(webx.XMLParser):
	def __init__(self, msg):
		self.icon = None;
		self.title = None;
		webx.XMLParser.__init__(self, msg);
	def process(self, tag, text):
		if self.icon == None and tag.lower() == 'link':
			tmp = self['rel'];
			if tmp and tmp.lower() in ('icon', 'mask-icon', 'shortcut icon'):
				self.icon = self['href'].strip();
		if text and self.title == None and tag.lower() == 'title': self.title = text;

def main(app):
	res = {'code': stdx.XG_FAIL};
	url = app.getParameter('url');
	if not stdx.CheckLength(url, (1, 1024)): res['code'] = stdx.XG_PARAMERR;
	else:
		try:
			data = webx.GetHttpResult(url, timeout = 1);
			res['code'] = stdx.XG_ERROR;
			if data.getheader('content-encoding') == 'gzip':
				msg = webx.gzipdecode(data.read()).decode(errors = 'ignore');
			else:
				msg = data.read().decode(errors = 'ignore');
			if msg:
				res['code'] = stdx.XG_OK;
				page = PageParser(msg);
				title = page.title;
				icon = page.icon;
				if title: res['title'] = title;
				if icon:
					if icon[0:2] == '//':
						if data.host.crypted: res['icon'] = 'https:' + icon;
						else: res['icon'] = 'http:' + icon;
					else:
						if icon.lower().find('http://') < 0 and icon.lower().find('https://'): res['icon'] = data.host.site + '/' + icon.strip('/');
						else: res['icon'] = icon;
				else:
					if data.host.crypted: icon = 'https://' + data.host.host + '/favicon.ico';
					else: icon = 'http://' + data.host.host + '/favicon.ico';
					res['icon'] = icon;
		except:
			data = webx.GetInfoFromURL(url);
			res['title'] = data.host.replace('www.', '').replace('.com', '');
			res['icon'] = data.site + '/favicon.ico';
			res['code'] = stdx.XG_OK;
	return stdx.json(res);
